import 'package:flutter/material.dart';
import 'package:hzy_project_template/models/image_normal_model.dart';
import 'package:share_plus/share_plus.dart';

import 'image_picker_tool.dart';
import 'utils.dart';

class ShareTool {
  /*
   * 分享图片
   * {
   *    content: 上下文
   *    list: 分享图片资源
   * }
   */
  static Future<ShareResult?> shareImage({
    required BuildContext context,
    List<ImageNormalModel>? list,
  }) async {
    final box = context.findRenderObject() as RenderBox?;
    if (list != null) {
      List<XFile> xlist = await ImagePickerTool.configImageConversion(
        list: list,
      );
      loadDismiss();
      final shareResult = await Share.shareXFiles(
        xlist,
        sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size,
      );
      if (shareResult.status == ShareResultStatus.success) {
        showToastMsg("分享成功");
      }
      return shareResult;
    } else {
      showToastMsg("请选择要分享的图片");
      return null;
    }
  }

  /* 
   * 分享文本
   * {
   *    text:分享文案,
   *    context:上下文,
   *    subject:小标题,
   * }
   */
  static shareText({
    required String text,
    BuildContext? context,
    String? subject,
    Rect? sharePositionOrigin,
  }) async {
    ScaffoldMessengerState? scaffoldMessenger;
    if (context != null) {
      final box = context.findRenderObject() as RenderBox?;
      sharePositionOrigin ??= box!.localToGlobal(Offset.zero) & box.size;
      scaffoldMessenger = ScaffoldMessenger.of(context);
    }
    ShareResult shareResult = await Share.shareWithResult(
      text,
      subject: subject,
      sharePositionOrigin: sharePositionOrigin,
    );
    scaffoldMessenger?.showSnackBar(getResultSnackBar(shareResult));
  }

  /// 分享结果显示
  static SnackBar getResultSnackBar(ShareResult result) {
    return SnackBar(
      content: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text("Share result: ${result.status}"),
          if (result.status == ShareResultStatus.success)
            Text("Shared to: ${result.raw}")
        ],
      ),
    );
  }
}
